﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Media.Imaging;

namespace ManYor.Phone.Common
{
    /// <summary>
    /// Image延迟加载DP
    /// </summary>
    public static class ImageLazyLoader
    {
        /// <summary>
        /// 下载
        /// </summary>
        private static DownloadHelper dwHelper;
        /// <summary>
        /// 缓存管理器
        /// </summary>
        private static IsolateCache cache;
        /// <summary>
        /// 静态构造函数
        /// </summary>
        static ImageLazyLoader()
        {
            dwHelper = new DownloadHelper();
            cache = new IsolateCache();
        }

        #region -- DP 相关
        /// <summary>
        /// 依赖属性
        /// </summary>
        public static readonly DependencyProperty UriSourceProperty = DependencyProperty.RegisterAttached(
            "UriSource", 
            typeof(Uri), 
            typeof(ImageLazyLoader),
            new PropertyMetadata(UriSourcePropertyChangedCallback));
            
        /// <summary>
        /// Get
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static Uri GetUriSource(Image obj)
        {
            if (null == obj)
            {
                throw new ArgumentNullException("obj");
            }
            return (Uri)obj.GetValue(UriSourceProperty);
        }
        /// <summary>
        /// Set
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="value"></param>
        public static void SetUriSource(Image obj, Uri value)
        {
            if (null == obj)
            {
                throw new ArgumentNullException("obj");
            }
            obj.SetValue(UriSourceProperty, value);
        }
        /// <summary>
        /// DP 回调
        /// </summary>
        /// <param name="d"></param>
        /// <param name="e"></param>
        public static void UriSourcePropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var image = d as Image;
            var uri = e.NewValue as Uri;
            var fileKey=System.IO.Path.GetFileName(uri.AbsoluteUri);

            //从缓存中读取
            if (cache.ContainKey(fileKey))
            {
                BitmapImage bmp = cache.GetImageFormCache(fileKey);
                image.Source = bmp;
            }
            else
            {
                //如果缓存中木有,则从网络下载
                dwHelper.StartRequest(uri.AbsoluteUri, UriKind.Absolute, new PendingRequest(image, uri), RequestCompletedHandler);
            }
        }        
        #endregion

        /// <summary>
        /// 下载完成的回调
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private static void RequestCompletedHandler(object sender, OpenReadCompletedEventArgs args)
        {
            PendingRequest request = args.UserState as PendingRequest;
            var fileKey = System.IO.Path.GetFileName(request.Uri.AbsoluteUri);
            //缓存图片
            if (!cache.ContainKey(fileKey))
            {
                cache.CacheImage(fileKey, args.Result);
            }
            BitmapImage bmp = new BitmapImage();
            bmp.SetSource(args.Result);
            request.Image.Source = bmp;
        }
    }
    /// <summary>
    ///  挂起的请求
    /// </summary>
    public class PendingRequest
    {
        public Image Image { get; private set; }
        public Uri Uri { get; private set; }
        public PendingRequest(Image image, Uri uri)
        {
            Image = image;
            Uri = uri;
        }
    }
}
